package cool.zhoujie.fragment;

import android.annotation.SuppressLint;
import android.os.AsyncTask;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import cool.zhoujie.Constant;
import cool.zhoujie.MainActivity;
import cool.zhoujie.R;
import cool.zhoujie.adapter.DailyAdapter;

import cool.zhoujie.db.DBUtil;
import cool.zhoujie.db.RecentPlay;
import cool.zhoujie.gson.Data_Rec;
import cool.zhoujie.gson.Gson_MoreSong;
import cool.zhoujie.gson.Gson_Rec;
import cool.zhoujie.service.PlayService;
import cool.zhoujie.util.HttpResponse;
import cool.zhoujie.util.HttpUtil;

/**
 * 每日推荐碎片
 */
public class DailyRecFragment extends BaseLazyLoadFragment {

    private List<Data_Rec> recList = new ArrayList<>();

    private ListView listView;

    private TextView loading;

    private Data_Rec data_rec;

    private PlayService.PlayBinder binder;

    private MainActivity activity;

    private PlayFragment playFragment;

    private RecentPlay recentPlay;

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_daily_rec, container, false);
        listView = view.findViewById(R.id.daily_listView);
        loading = view.findViewById(R.id.daily_loading);
        activity = (MainActivity) getActivity();
        playFragment = (PlayFragment) activity.getSupportFragmentManager().findFragmentByTag("fragment_songPlay");
        return view;
    }

    @Override
    public void initEvent() {
        //listView点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                data_rec = recList.get(position);
                doPlay(data_rec);
            }
        });
    }

    @Override
    public void onLazyLoad() {
        new DailyTask().execute();
    }

    private void doPlay(final Data_Rec data_rec) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtil.sendHttpRequest(Constant.More_song + data_rec.song_id, new HttpResponse() {
                    @Override
                    public void showLoading() {

                    }

                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        Gson_MoreSong moreSong = gson.fromJson(response, Gson_MoreSong.class);

                        recentPlay = new RecentPlay();
                        recentPlay.songPath = moreSong.moreSong.songLink;
                        recentPlay.songName = moreSong.moreSong.songName;
                        recentPlay.artistName = moreSong.moreSong.artistName;
                        recentPlay.songPic = moreSong.moreSong.songPic;

                        binder = activity.playBinder;
                        PlayService playService = binder.getService();
                        playService.initMediaPlayer(recentPlay.songPath);
                        playService.play();

                        saveRecent(recentPlay);

                        informPlayFragment(recentPlay);
                    }
                });
            }
        }).start();
    }

    private void saveRecent(RecentPlay recentPlay) {
        List<RecentPlay> recentPlayList = DBUtil.queryAll();
        for (int i = 0; i < recentPlayList.size(); i++) {
            RecentPlay recentPlay1 = recentPlayList.get(i);
            if (recentPlay1.songName.equals(recentPlay.songName) && recentPlay1.artistName.equals(recentPlay.artistName)) {
                DBUtil.delete(recentPlay1);
                Log.d(Constant.TAG_DB, "数据重复，删除成功");
            }
        }
        DBUtil.insert(recentPlay);
    }

    private void informPlayFragment(RecentPlay recentPlay) {
        playFragment.current_state = PlayFragment.STATE_PLAY;
        playFragment.updateView(recentPlay);
    }

    @SuppressLint("StaticFieldLeak")
    class DailyTask extends AsyncTask<Void,Void,List<Data_Rec>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            listView.setVisibility(View.GONE);
            loading.setVisibility(View.VISIBLE);
        }

        /**
         * 在子线程运行，处理耗时任务
         * @param voids 可变参数列表，空
         * @return 请求成功返回true，否则为false
         */
        @Override
        protected List<Data_Rec> doInBackground(Void... voids) {
            HttpUtil.sendHttpRequest(Constant.Rec_daily, new HttpResponse() {
                @Override
                public void showLoading() {

                }

                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    Gson_Rec rec = gson.fromJson(response, Gson_Rec.class);
                    recList = rec.recList;
                }
            });
            return recList;
        }

        @Override
        protected void onPostExecute(List<Data_Rec> data_recs) {
            listView.setVisibility(View.VISIBLE);
            loading.setVisibility(View.GONE);
            DailyAdapter adapter = new DailyAdapter(getContext(), R.layout.list_view_item, data_recs);
            listView.setAdapter(adapter);
        }
    }

}
